<template>
  <div class="container">
    <div class="app-container">
      <!-- 操作按钮 -->
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="isOpen = true"
        >添加角色</el-button>
      </div>

      <!-- table组件 -->
      <el-table v-loading="isLoading" :data="roleList" width="100%">
        <!-- 角色名称列 -->
        <el-table-column align="center" label="角色" prop="name" width="200px">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <!-- 启用列-->
        <el-table-column align="center" label="启用" prop="state" width="200px">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1 ? "已启用" : "未启用" }}</span>
          </template>
        </el-table-column>
        <!-- 描述列 -->
        <el-table-column align="center" label="描述" prop="description">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              :rows="2"
              size="mini"
              type="textarea"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column align="center" label="操作" prop="name">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button
                size="mini"
                type="primary"
                @click="confirmEdit(row)"
              >确认</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button icon="el-icon-lock" type="text">分配权限</el-button>
              <el-button
                icon="el-icon-edit"
                type="text"
                @click="editRole(row)"
              >编辑</el-button>
              <el-popconfirm title="确定删除该员工吗？" @onConfirm="deleteRole(row.id)">
                <el-button
                  slot="reference"
                  icon="el-icon-delete"
                  type="text"
                  style="margin-left: 10px"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          background
          layout="prev, pager, next"
          @current-change="pageChange"
        />
      </div>
    </div>

    <!-- 添加角色弹框 -->
    <el-dialog
      :visible.sync="isOpen"
      title="添加角色"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            :rows="3"
            size="mini"
            type="textarea"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="addRole"
          >确认</el-button>
          <el-button size="mini" @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  roleListService,
  roleAddService,
  roleUpdateService,
  roleDeleteService
} from '@/api/role'

export default {
  name: 'Role',
  data() {
    return {
      isLoading: false, // 控制加载状态
      isOpen: false, // 控制弹框显示
      roleList: [], // 角色列表
      // 分页参数
      pageParams: {
        total: 0, // 总条数
        page: 1, // 当前页码数
        pagesize: 5 // 每页显示条数
      },
      // 添加角色表单数据
      roleForm: {
        name: '', // 角色名称
        state: 0, // 启用状态
        description: '' // 角色描述
      },
      // 添加角色表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.isLoading = true
      const { total, rows: roleList } = await roleListService(this.pageParams)
      this.pageParams.total = total
      this.roleList = roleList
      this.isLoading = false
      this.roleList.forEach((item) => {
        // 添加响应式编辑状态属性
        this.$set(item, 'isEdit', false)
        // 缓存编辑前数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 分页切换
    pageChange(currentPage) {
      this.pageParams.page = currentPage
      this.getRoleList()
    },
    // 添加角色
    addRole() {
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) return
        // 提交表单
        await roleAddService(this.roleForm)
        this.$message.success('添加角色成功')
        // 更新总条数
        this.pageParams.total += 1
        // 计算并跳转到最后一页
        const newPage = Math.ceil(
          this.pageParams.total / this.pageParams.pagesize
        )
        // 确保 getRoleList 完成后再关闭对话框和更新页码
        await this.getRoleList()
        this.closeDialog()
        this.pageChange(newPage)
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.isOpen = false
      this.$refs.roleForm.resetFields()
    },
    // 编辑角色
    editRole(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 确认编辑
    async confirmEdit(row) {
      if (row.editRow.name && row.editRow.description) {
        // 提交编辑数据
        await roleUpdateService({ id: row.id, ...row.editRow })
        this.$message.success('编辑角色成功')
        Object.assign(row, {
          ...this.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述不能为空！')
      }
    },
    // 取消编辑
    cancelEdit(row) {
      row.isEdit = false
    },
    // 删除角色
    async deleteRole(id) {
      const currentPage = Math.ceil((this.pageParams.total - 1) / this.pageParams.pagesize)
      // 删除角色
      await roleDeleteService(id)
      // 更新总条数
      this.$message.success('删除角色成功!')
      this.pageChange(currentPage)
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  .app-container {
    .role-operate {
      padding: 10px;
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
      padding: 0 10px 10px 10px;
    }
  }
}
</style>
